
// 导入 Ant Design Mobile 组件库
import { Form, Input, Button, Toast, NavBar, Tabs } from 'antd-mobile'
// 导入 React Router 的导航钩子，用于页面跳转
import { useNavigate } from 'react-router-dom'
// 导入自定义请求工具，用于与后端 API 通信
import request from '../../api/request.tsx'
// 导入 RSA 加密工具，用于密码加密
import { encryptPassword } from '../../utils/rsa'
import { getUserRole } from '../../utils/permission'

// 导入 Redux 的 dispatch 钩子，用于状态管理
import { useDispatch } from 'react-redux'
// 导入 Redux action，用于设置用户信息
import { setinfo } from '../../store/Info'
// 导入 React 的 useState 钩子，用于本地状态管理
import { useState, useEffect, useRef } from 'react'
// 导入样式文件
import './index.css'
// 导入 Ant Design Mobile 图标
import { LeftOutline, UserOutline } from 'antd-mobile-icons'
// 导入人脸识别相关组件
import FaceCamera from '../../components/FaceCamera'
import FaceQualityCheck from '../../components/FaceQualityCheck'
// 导入人脸识别API
import { detectFace, searchFaces, fileToBase64 } from '../../api/faceRecognition'
// 导入人脸登录API
import { checkFaceRegistered } from '../../api/faceLogin'

/**
 * 登录表单数据接口
 * 定义了登录表单的字段结构
 */
interface LoginFormValues {
  email: string    // 用户邮箱/账号
  pwd: string      // 用户密码
}

/**
 * 登录页面组件
 * 提供用户登录功能，包括表单验证、密码加密、状态管理等
 */
function Login() {
  // 获取路由导航函数，用于页面跳转
  const navigate = useNavigate()
  // 获取 Redux dispatch 函数，用于更新全局状态
  const dispatch = useDispatch()
  
  // ==================== 本地状态管理 ====================
  
  /**
   * 邮箱输入框的值
   * 用于控制输入框的显示内容
   */
  const [emailValue, setEmailValue] = useState('')
  // 登录模式: account(账号密码) | sms(手机验证码) | face(人脸识别)
  const [loginMode, setLoginMode] = useState<'account' | 'sms' | 'face'>('account')
  // 短信登录字段
  const [phoneValue, setPhoneValue] = useState('')
  const [smsCode, setSmsCode] = useState('')
  const [counter, setCounter] = useState(0)
  const timerRef = useRef<number | null>(null)
  
  /**
   * 密码输入框的值
   * 用于控制密码输入框的显示内容
   */
  const [passwordValue, setPasswordValue] = useState('')

  // ==================== 人脸登录相关状态 ====================
  
  // 人脸摄像头显示状态
  const [showFaceCamera, setShowFaceCamera] = useState(false)
  // 人脸质量检测结果
  const [faceQualityResult, setFaceQualityResult] = useState<{
    isValid: boolean
    message: string
    details?: Record<string, unknown>
    imageData?: string
    faceData?: Record<string, unknown>
  } | null>(null)
  // 显示人脸质量检测组件
  const [showFaceQualityCheck, setShowFaceQualityCheck] = useState(false)
  // 人脸登录状态
  const [isFaceLogging, setIsFaceLogging] = useState(false)

  // ==================== 事件处理函数 ====================
  
  /**
   * 登录表单提交处理函数
   * 处理用户登录逻辑，包括表单验证、API 请求、状态更新等
   * 
   * @param values 表单提交的数据，包含 email 和 pwd 字段
   */
  const onFinish = async (values: LoginFormValues) => {
    try {
      // 邮箱格式验证：使用正则表达式验证邮箱格式
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(values.email)) {
        Toast.show('请输入正确的邮箱格式')
        return
      }

      // 调用真实API接口
      const response = await request.post('/health/user/v1/login', {
        email: values.email,
        pwd: encryptPassword(values.pwd)
      })

      // 获取响应数据
      const data = response.data
      console.log(data);
      
      // 检查登录是否成功
      if (data && data.status === '0000') {
        const result = data.result || {}
        
        // 保存会话ID到本地存储，用于后续请求的身份验证
        if (result.sessionId) {
          localStorage.setItem('token', result.sessionId)
          localStorage.setItem('sessionId', result.sessionId)
        }
        
        // 保存用户ID到本地存储，用于用户身份识别
        if (result.userId) {
          localStorage.setItem('userId', String(result.userId))
        }
        
        // 保存用户邮箱到本地存储
        const userEmail = result.email || values.email
        localStorage.setItem('email', userEmail)
        
        // 保存用户名到本地存储（如果有的话）
        if (result.userName) {
          localStorage.setItem('userName', result.userName)
        }
        
        // 获取用户角色并保存到本地存储
        const userRole = getUserRole(userEmail)
        localStorage.setItem('userRole', userRole)
        
        // 显示登录成功提示
        const roleText = userRole === 'admin' ? '管理员' : '普通用户'
        Toast.show(`登录成功，欢迎${roleText}！`)
        
        // 更新 Redux 全局状态，保存用户信息
        dispatch(setinfo({
          email: result.email || values.email,      // 用户邮箱
          userId: result.userId || '',              // 用户ID
          userName: result.userName || '',          // 用户名
          role: userRole                            // 用户角色
        }))
        
        // 登录成功后跳转到之前保存的路径或首页
        const redirectPath = localStorage.getItem('redirectPath')
        if (redirectPath && redirectPath !== '/login') {
          localStorage.removeItem('redirectPath') // 清除保存的路径
          navigate(redirectPath)
        } else {
          navigate('/')
        }
      } else {
        // 登录失败，显示错误信息
        Toast.show(data?.message || '登录失败')
      }
    } catch (error) {
      // 网络错误或其他异常处理
      Toast.show('登录失败，请稍后重试')
      console.error('登录错误:', error)
    }
  }

  // 发送短信验证码
  const sendSmsCode = async () => {
    const phoneRegex = /^(1[3-9])\d{9}$/
    if (!phoneRegex.test(phoneValue)) {
      Toast.show('请输入正确的手机号')
      return
    }
    try {
      // 根据后端实际接口调整
      const resp = await request.post('/health/user/verify/v1/sendSmsCode', { phone: phoneValue })
      const data = resp?.data || {}
      if (data.status === '0000') {
        Toast.show('验证码已发送')
        // 开始60s倒计时
        setCounter(60)
        if (timerRef.current) window.clearInterval(timerRef.current)
        timerRef.current = window.setInterval(() => {
          setCounter((prev) => {
            if (prev <= 1) {
              if (timerRef.current) window.clearInterval(timerRef.current)
              timerRef.current = null
              return 0
            }
            return prev - 1
          })
        }, 1000)
      } else {
        Toast.show(data.message || '发送失败')
      }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (e) {
      Toast.show('发送失败，请稍后重试')
    }
  }

  // （移除 GitHub 登录，保留 Gitee 登录）

  // Gitee登录处理
  const handleGiteeLogin = () => {
    // Gitee OAuth 应用配置
    const clientId = 'fb2428e600444232b42e6e440fa526a268a93e12daa6ab0bea2f938b47cdcfb6' // 你的Gitee OAuth App Client ID
    const redirectUri = encodeURIComponent(`${window.location.origin}/auth/gitee/callback`)
    const scope = 'user_info emails'
    
    // 构建Gitee授权URL
    const giteeAuthUrl = `https://gitee.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}&response_type=code&state=${Date.now()}`
    
    // 跳转到Gitee授权页面
    window.location.href = giteeAuthUrl
  }

  // ==================== 人脸登录处理函数 ====================
  
  /**
   * 开始人脸登录
   */
  const handleFaceLogin = async () => {
    // 先检查用户是否已注册人脸
    const userId = localStorage.getItem('userId')
    if (!userId) {
      Toast.show('请先使用账号密码登录，然后注册人脸')
      return
    }

    try {
      // 检查人脸注册状态
      const response = await checkFaceRegistered(userId)
      if (response.data?.result?.isRegistered) {
        setShowFaceCamera(true)
      } else {
        Toast.show({
          content: '您还未注册人脸，请先使用账号密码登录并注册人脸',
          duration: 3000
        })
      }
    } catch (error) {
      // 如果检查接口不存在，直接进入人脸识别流程
      console.log('人脸注册状态检查失败，直接进入人脸识别流程')
      setShowFaceCamera(true)
    }
  }

  /**
   * 处理人脸图片捕获
   */
  const handleFaceCapture = async (imageData: string) => {
    try {
      setIsFaceLogging(true)
      setShowFaceCamera(false)
      
      // 将base64图片转换为File对象
      const response = await fetch(imageData)
      const blob = await response.blob()
      const file = new File([blob], 'face.jpg', { type: 'image/jpeg' })
      
      // 转换为base64格式
      const base64 = await fileToBase64(file)
      
      // 进行人脸检测和质量评估
      const detectResult = await detectFace(base64)
      
      if (!detectResult.success) {
        Toast.show(detectResult.message)
        setIsFaceLogging(false)
        return
      }

      // 设置质量检测结果
      setFaceQualityResult({
        isValid: true,
        message: detectResult.message,
        details: detectResult.data?.quality,
        imageData: base64,
        faceData: detectResult.data
      })
      
      setShowFaceQualityCheck(true)
      setIsFaceLogging(false)
    } catch (error) {
      console.error('人脸捕获处理错误:', error)
      Toast.show('人脸识别失败，请重试')
      setIsFaceLogging(false)
    }
  }

  /**
   * 重新拍摄人脸
   */
  const handleFaceRetry = () => {
    setShowFaceQualityCheck(false)
    setFaceQualityResult(null)
    setShowFaceCamera(true)
  }

  /**
   * 确认使用人脸进行登录
   */
  const handleFaceConfirm = async () => {
    if (!faceQualityResult?.imageData) {
      Toast.show('人脸数据异常，请重新拍摄')
      return
    }

    try {
      setIsFaceLogging(true)
      setShowFaceQualityCheck(false)
      
      // 使用人脸M:N搜索进行登录
      const searchResult = await searchFaces(faceQualityResult.imageData, 'user_faces')
      
      if (searchResult.success && searchResult.data) {
        const bestMatch = searchResult.data.faceList[0].userList[0]
        
        // 保存登录信息
        localStorage.setItem('token', `face_token_${Date.now()}`)
        localStorage.setItem('sessionId', `face_session_${Date.now()}`)
        localStorage.setItem('userId', bestMatch.userId)
        localStorage.setItem('email', bestMatch.userInfo || 'face_user@example.com')
        localStorage.setItem('userName', bestMatch.userInfo || '人脸用户')
        
        const userEmail = bestMatch.userInfo || 'face_user@example.com'
        const userRole = getUserRole(userEmail)
        localStorage.setItem('userRole', userRole)
        
        Toast.show(`人脸登录成功！相似度: ${bestMatch.score.toFixed(1)}分`)
        
        // 显示详细成功信息
        Toast.show({
          content: `人脸登录成功！\n用户: ${bestMatch.userInfo || '人脸用户'}\n相似度: ${bestMatch.score.toFixed(1)}分\n欢迎回来！`,
          duration: 3000,
          position: 'center'
        })
        
        // 更新 Redux 状态
        dispatch(setinfo({
          email: userEmail,
          userId: bestMatch.userId,
          userName: bestMatch.userInfo || '人脸用户',
          role: userRole
        }))
        
        // 跳转到首页
        const redirectPath = localStorage.getItem('redirectPath')
        if (redirectPath && redirectPath !== '/login') {
          localStorage.removeItem('redirectPath')
          navigate(redirectPath)
        } else {
          navigate('/')
        }
      } else {
        // 人脸搜索失败
        Toast.show({
          content: searchResult.message || '人脸登录失败，请先注册人脸',
          duration: 3000
        })
      }
    } catch (error: unknown) {
      console.error('人脸登录错误:', error)
      Toast.show('人脸登录失败，请重试')
    } finally {
      setIsFaceLogging(false)
      setFaceQualityResult(null)
    }
  }

  /**
   * 关闭人脸摄像头
   */
  const handleFaceCameraClose = () => {
    setShowFaceCamera(false)
    setIsFaceLogging(false)
  }



  useEffect(() => {
    return () => {
      if (timerRef.current) window.clearInterval(timerRef.current)
    }
  }, [])

  // 短信登录
  const onSmsLogin = async () => {
    const phoneRegex = /^(1[3-9])\d{9}$/
    if (!phoneRegex.test(phoneValue)) {
      Toast.show('请输入正确的手机号')
      return
    }
    if (!smsCode) {
      Toast.show('请输入验证码')
      return
    }
    try {
      const resp = await request.post('/health/user/verify/v1/loginBySms', {
        phone: phoneValue,
        code: smsCode
      })
      const data = resp?.data
      if (data && data.status === '0000') {
        const result = data.result || {}
        if (result.sessionId) {
          localStorage.setItem('token', result.sessionId)
          localStorage.setItem('sessionId', result.sessionId)
        }
        if (result.userId) {
          localStorage.setItem('userId', String(result.userId))
        }
        // 保存邮箱/手机号标识
        localStorage.setItem('email', result.email || '')
        if (result.userName) {
          localStorage.setItem('userName', result.userName)
        }
        dispatch(setinfo({
          email: result.email || '',
          userId: result.userId || '',
          userName: result.userName || '',
          role: localStorage.getItem('userRole') || ''
        }))
        Toast.show('登录成功')
        navigate('/')
      } else {
        Toast.show(data?.message || '登录失败')
      }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (e) {
      Toast.show('登录失败，请稍后重试')
    }
  }

  // ==================== 组件渲染 ====================
  
  return (
    <div className="login-container">
      {/* 顶部导航栏 */}
      <NavBar
        className="sticky-navbar"
        backArrow={<LeftOutline />}
        onBack={() => navigate('/')}
        style={{
          '--border-bottom': '1px solid #f0f0f0'
        }}
      >
        <div className="nav-content">
          <span>登录</span>
          <span className="nav-link" onClick={() => navigate('/zhuce')}>
            去注册
          </span>
        </div>
      </NavBar>
      
      <div className="login-content">
        {/* 应用图标区域 */}
        <div className="app-icon">
          {/* 大图标气泡 */}
          <div className="icon-bubble large">
            <span className="plus">+</span>
          </div>
          {/* 小图标气泡 */}
          <div className="icon-bubble small">
            <span className="dots">••</span>
          </div>
        </div>

        {/* 登录表单区域 */}
        <div className="login-form-container">
          <Tabs activeKey={loginMode} onChange={(k) => setLoginMode(k as 'account' | 'sms' | 'face')}>
            <Tabs.Tab title='账号登录' key='account'>
              <Form
                layout='vertical'
                onFinish={onFinish}
                style={{ width: '100%' }}
              >
                {/* 输入框组 */}
                <div className="input-group">
                  {/* 账号输入框 */}
                  <div className="input-field">
                    <div className="input-row">
                      <label className="input-label">账号</label>
                      <Form.Item
                        name='email'
                        rules={[{ required: true, message: '请输入账号' }]}
                        style={{ margin: 0, flex: 1 }}
                      >
                        <Input 
                          placeholder='' 
                          value={emailValue}
                          onChange={(value) => setEmailValue(value)}
                          style={{
                            border: 'none',
                            background: 'transparent',
                            fontSize: '16px',
                            padding: '12px 0',
                            textAlign: 'left',
                            color: '#2c3e50',
                            fontWeight: '500'
                          }}
                        />
                      </Form.Item>
                    </div>
                  </div>
                  
                  {/* 输入框分隔线 */}
                  <div className="input-divider"></div>
                  
                  {/* 密码输入框 */}
                  <div className="input-field">
                    <div className="input-row">
                      <label className="input-label">密码</label>
                      <Form.Item
                        name='pwd'
                        rules={[{ required: true, message: '请输入密码' }]}
                        style={{ margin: 0, flex: 1 }}
                      >
                        <Input 
                          placeholder='' 
                          type='password'
                          value={passwordValue}
                          onChange={(value) => setPasswordValue(value)}
                          style={{
                            border: 'none',
                            background: 'transparent',
                            fontSize: '16px',
                            padding: '12px 0',
                            textAlign: 'left',
                            color: '#2c3e50',
                            fontWeight: '500'
                          }}
                        />
                      </Form.Item>
                    </div>
                  </div>
                </div>

                {/* 按钮组 */}
                <div className="button-group">
                  <Button
                    block
                    type='submit'
                    color='primary'
                    size='large'
                    style={{
                      height: '48px',
                      borderRadius: '8px',
                      fontSize: '16px',
                      fontWeight: '500',
                      marginBottom: '16px',
                      backgroundColor: '#1890ff',
                      border: 'none'
                    }}
                  >
                    登录
                  </Button>
                  <Button
                    block
                    size='large'
                    style={{
                      height: '48px',
                      borderRadius: '8px',
                      fontSize: '16px',
                      fontWeight: '500',
                      backgroundColor: '#fff',
                      border: '1px solid #d9d9d9',
                      color: '#666'
                    }}
                    onClick={(event) => {
                      event.preventDefault();
                      Toast.show('找回密码功能开发中...');
                    }}
                  >
                    找回密码
                  </Button>
                </div>
              </Form>
            </Tabs.Tab>
            <Tabs.Tab title='验证码登录' key='sms'>
              <div className="sms-login" style={{ width: '100%' }}>
                <div className="input-group">
                  <div className="input-field">
                    <div className="input-row">
                      <label className="input-label">手机号</label>
                      <Input value={phoneValue} onChange={setPhoneValue} placeholder='请输入手机号' type='tel' style={{ border: 'none', background: 'transparent', fontSize: '16px', padding: '12px 0', textAlign: 'left', color: '#2c3e50', fontWeight: '500' }} />
                    </div>
                  </div>
                  <div className="input-divider"></div>
                  <div className="input-field">
                    <div className="input-row" style={{ alignItems: 'center' }}>
                      <label className="input-label">验证码</label>
                      <div style={{ display: 'flex', flex: 1, gap: 8, alignItems: 'center' }}>
                        <Input value={smsCode} onChange={setSmsCode} placeholder='请输入验证码' style={{ border: 'none', background: 'transparent', fontSize: '16px', padding: '12px 0', textAlign: 'left', color: '#2c3e50', fontWeight: '500', flex: 1 }} />
                        {counter > 0 ? (
                          <Button size='small' disabled>{counter}s</Button>
                        ) : (
                          <Button size='small' color='primary' onClick={sendSmsCode}>获取验证码</Button>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
                <div className="button-group">
                  <Button block color='primary' size='large' style={{ height: '48px', borderRadius: '8px', fontSize: '16px', fontWeight: '500', backgroundColor: '#1890ff', border: 'none' }} onClick={onSmsLogin}>登录</Button>
                </div>
              </div>
            </Tabs.Tab>
            <Tabs.Tab title='人脸登录' key='face'>
              <div className="face-login" style={{ width: '100%' }}>
                <div className="face-login-content">
                  <div className="face-login-icon">
                    <UserOutline style={{ fontSize: '48px', color: '#1890ff' }} />
                  </div>
                  <h3 className="face-login-title">人脸识别登录</h3>
                  <p className="face-login-desc">
                    使用人脸识别技术，安全便捷地登录系统
                  </p>
                  <div className="face-login-tips">
                    <p>• 请确保光线充足</p>
                    <p>• 保持人脸正面面对摄像头</p>
                    <p>• 避免遮挡面部特征</p>
                  </div>
                               <Button
               block
               color='primary'
               size='large'
               onClick={handleFaceLogin}
               loading={isFaceLogging}
               style={{
                 height: '48px',
                 borderRadius: '8px',
                 fontSize: '16px',
                 fontWeight: '500',
                 backgroundColor: '#1890ff',
                 border: 'none',
                 marginTop: '24px'
               }}
             >
               {isFaceLogging ? '识别中...' : '开始人脸识别'}
             </Button>
                </div>
              </div>
            </Tabs.Tab>
          </Tabs>

          {/* 第三方登录区域 */}
          <div className="third-party-login">
            <div className="divider">
              <span>或</span>
            </div>
            
            <div className="third-party-buttons">
              <Button
                className="gitee-login-btn"
                onClick={handleGiteeLogin}
                style={{
                  height: '44px',
                  borderRadius: '8px',
                  fontSize: '14px',
                  fontWeight: '500',
                  backgroundColor: '#c71d23',
                  border: 'none',
                  color: 'white',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: '8px'
                }}
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M11.984 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.016 0zm6.09 5.333c.328 0 .593.266.593.593v1.482a.594.594 0 0 1-.593.593H9.777c-.982 0-1.778.796-1.778 1.778v5.63c0 .982.796 1.778 1.778 1.778h8.296c.982 0 1.778-.796 1.778-1.778v-5.63c0-.982-.796-1.778-1.778-1.778H18.37z"/>
                </svg>
                Gitee 登录
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 人脸识别摄像头组件 */}
      <FaceCamera
        isVisible={showFaceCamera}
        onCapture={handleFaceCapture}
        onClose={handleFaceCameraClose}
        title="人脸识别登录"
      />

      {/* 人脸质量检测组件 */}
      <FaceQualityCheck
        isVisible={showFaceQualityCheck}
        qualityResult={faceQualityResult}
        onRetry={handleFaceRetry}
        onConfirm={handleFaceConfirm}
      />
    </div>
  )
}

// 导出登录组件
export default Login
